package com.myapp.struts;

import hibernate.Clientes;
import hibernate.Usuarios;
import hibernate.UsuariosDAO;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginAction extends org.apache.struts.action.Action {

    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        LoginForm f = (LoginForm) form;
        UsuariosDAO dao = new UsuariosDAO();

        Usuarios usuario = dao.get(f.getUsuario(), f.getPassword());

        if (usuario == null || !usuario.getPerfil().equals("cliente")) {
            request.setAttribute("msg2", "El usuario y/o la clave son incorrectas");
            return mapping.findForward(FAILURE);
        } else {
            HttpSession session = request.getSession(true);
            session.setMaxInactiveInterval(180);
            session.setAttribute("login",true);
            session.setAttribute("time", new Date());
            session.setAttribute("dni", usuario.getUsuario());
            session.setAttribute("perfil", usuario.getPerfil());          
            // subir a session el objeto cliente con el que se trabaja
            Iterator it = usuario.getClienteses().iterator();
            while (it.hasNext()) {
                Clientes cliente =(Clientes) it.next();
                session.setAttribute("cliente", cliente);
            }
                      
            return mapping.findForward(SUCCESS);
        }

    }
}
